import 'package:aichat_flutter_wallet/module_common/network/rpc_http.dart';
import 'package:aichat_flutter_wallet/module_common/provider/token_list_provider.dart';
import 'package:aichat_flutter_wallet/module_common/provider/wallet_info_provider.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/page_status_com.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/token_widget/token_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';
import 'package:lib_language/lib_language.dart';
import 'bottom_sheet_widget.dart';

class SelectTokenDialog extends StatefulWidget {
  final String? title;
  final Token? token;
  const SelectTokenDialog({super.key, this.title, this.token});

  @override
  State<StatefulWidget> createState() {
    return _SelectTokenDialogState();
  }
}

class _SelectTokenDialogState extends State<SelectTokenDialog> {
  late int selectedWalletInfoId; //当前钱包ID
  late List<WalletInfo> walletInfoList;
  late List<Token> tokenList; //当前代币列表
  List<int> walletList = [];

  ScrollController scrollController = ScrollController();
  @override
  void initState() {
    super.initState();
    selectedWalletInfoId = widget.token!.walletInfoId;
    walletInfoList =
        ObjectBox().walletInfoModel.getWalletInfoListByWalletId(context.read<WalletInfoNotifier>().walletId);
    tokenList = ObjectBox().tokenModel.getFungibleTokenListByWalletInfoId(selectedWalletInfoId);
    getTokensBalance();
    // Future.delayed(Duration.zero, () {
    //   int totalLength =
    //       walletInfoList.fold(0, (int previousValue, obj) => previousValue + obj.getChain()!.name.toString().length);
    //   int index = walletInfoList.indexWhere((element) => element.id == selectedWalletInfoId);
    //   double scrollWidth = totalLength * 7 + index * 10;
    //   scrollController.animateTo(scrollWidth, duration: Duration(milliseconds: 500), curve: Curves.ease);
    // });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      try {
        int index = walletInfoList.indexWhere((element) => element.id == selectedWalletInfoId);
        int totalLength = walletInfoList
            .sublist(0, index)
            .fold(0, (int previousValue, obj) => previousValue + obj.getChain()!.name.toString().length);
        double scrollWidth = totalLength * 7 + index * 10;
        scrollController.animateTo(scrollWidth.w, duration: Duration(milliseconds: 500), curve: Curves.ease);
      } catch (e) {}
    });
  }

  getTokensBalance() async {
    if (walletList.indexOf(selectedWalletInfoId) != -1) return;
    int id = selectedWalletInfoId;
    walletList.add(id);
    tokenList.forEach((element) {
      context.read<TokenListNotifier>().updateTokenBalance(element).then((val) {
        if (mounted && id == selectedWalletInfoId)
          setState(() {
            element = val;
          });
      });
      getTokenPrice(element.symbol).then((data) {
        element.change24h = data["change24h"];
        element.priceusd = data["priceusd"];
        ObjectBox().tokenModel.updateToken(element);
        if (mounted && id == selectedWalletInfoId) {
          setState(() {
            element = element;
          });
        }
      });
    });
  }

  Future getTokenPrice(String symbol) async {
    List<String> symbols = ['${symbol.toUpperCase()}USDT'];
    Map<String, dynamic> tokenUData = await RPCHttp().getTokenListIncreaseU(symbols);
    if (symbol.toUpperCase() == 'USDT') {
      return {"change24h": '0.00', "priceusd": '1'};
    } else
      return {
        "change24h": tokenUData['${symbol.toUpperCase()}USDT']["change"],
        "priceusd": tokenUData['${symbol.toUpperCase()}USDT']["priceU"]
      };
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BottomSheetWidget(
        title: widget.title ?? LocaleKeys.qingshuruqianbaomima.tr(),
        expand: false,
        child: Column(
          children: [
            Container(
              height: 30.w,
              padding: EdgeInsets.only(left: 20.w),
              child: ListView.builder(
                  itemCount: walletInfoList.length,
                  scrollDirection: Axis.horizontal,
                  controller: scrollController,
                  itemBuilder: (_, index) {
                    WalletInfo info = walletInfoList[index];
                    bool selected = info.id == selectedWalletInfoId;
                    return InkWell(
                      onTap: () {
                        setState(() {
                          selectedWalletInfoId = walletInfoList[index].id;
                          tokenList = ObjectBox().tokenModel.getFungibleTokenListByWalletInfoId(selectedWalletInfoId);
                          getTokensBalance();
                        });
                      },
                      child: Container(
                        height: 32.w,
                        margin: EdgeInsets.only(right: 10.w),
                        padding: EdgeInsets.symmetric(horizontal: 10.w),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(4.w)),
                            color: selected ? AppColors.c_8667FE01 : AppColors.c_F6F6F6),
                        child: Text(
                          info.getChain()?.name ?? '',
                          style: TextStyle(
                              color: selected ? AppColors.c_1D0061 : AppColors.c_868391,
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w400),
                        ),
                      ),
                    );
                  }),
            ),
            SizedBox(
              height: 10.w,
            ),
            Container(
              height: 270.w,
              child: (tokenList.length > 0)
                  ? ListView.builder(
                      itemCount: tokenList.length,
                      itemBuilder: (_, index) {
                        return Container(
                          color: (widget.token!.walletInfoId != '' &&
                                  widget.token!.contract == tokenList[index].contract &&
                                  widget.token!.walletInfoId == tokenList[index].walletInfoId)
                              ? AppColors.c_F6F6F6
                              : AppColors.c_white,
                          child: TokenWidget(
                              token: tokenList[index],
                              onTap: () {
                                Navigator.of(context).pop(tokenList[index]);
                              }),
                        );
                      })
                  : PageEmptyCom(icon: 'assets/images/status/empty.png', title: 'No Blacklist Now'),
            )
          ],
        ));
  }
}
